package com.demo.data.other;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class PkgGraph {
	
	/**Example 1:
	 * pkg_graph = {
		"A": ["B"],
		"B": ["C", "D"],
		"C": ["D"],
		"D": ["F"],
		"E": ["D"],
		"F": []
		}
		pkg = "B"
		Output: ["F", "D", "C", "B"]
		
		Example 2:
		pkg_graph = {
		"A": ["B"],
		"B": ["C", "D"],
		"C": ["D"],
		"D": ["F"],
		"E": ["D"],
		"F": []
		}
		pkg = "A"
		Output: ["F", "D", "C", "B", "A"]
	 * @param args
	 */
	
	private static Map<String, String[]> data;
	static {
		data = new HashMap<>();
		data.put("A", new String[] {"B"});
		data.put("B", new String[] {"C", "D"});
		data.put("C", new String[] {"D"});
		data.put("D", new String[] {"F"});
		data.put("E", new String[] {"D"});
		data.put("F", new String[] {});
	}
	
	public static void main(String[] args) {
		String pkg = "A";
		Set<String> result = new HashSet<>();
		deal(data, pkg, result);
		System.out.println(result);
	}

	private static Set<String> deal(Map<String, String[]> data, String pkg, Set<String> result) {
		result.add(pkg);
		String[] relatives = data.get(pkg);
		if(relatives != null && relatives.length > 0) {
			for (String relative : relatives) {
				if(relative != null) {
					deal(data, relative, result);
				}
			}
		}
		return result;
	}

}
